<?php

namespace app\model\oa;

use think\Model;
use think\model\concern\SoftDelete;

class Disk extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'oa_disk';

    // 自动时间戳
    protected $autoWriteTimestamp = true;

    // 软删除字段
    protected $deleteTime = 'delete_time';

    // 类型常量
    const TYPE_FOLDER = 1;    // 文件夹
    const TYPE_FILE = 2;    // 文件

    // 可见性常量
    const VISIBILITY_PRIVATE = 1;   // 私有
    const VISIBILITY_PUBLIC = 2;    // 公开
    const VISIBILITY_SHARE = 3;     // 共享

    // 关联创建人
    public function creator()
    {
        return $this->belongsTo('app\model\admin\User', 'create_by', 'id');
    }

    // 关联父文件夹
    public function parent()
    {
        return $this->belongsTo('app\model\oa\Disk', 'parent_id', 'id');
    }

    // 关联子文件/文件夹
    public function children()
    {
        return $this->hasMany('app\model\oa\Disk', 'parent_id', 'id');
    }

    // 获取用户网盘文件列表
    public static function getUserDiskList($userId, $parentId = 0, $params = [])
    {
        $query = self::where('create_by', $userId)
            ->where('parent_id', $parentId)
            ->order('type', 'asc')
            ->order('name', 'asc');

        // 类型筛选
        if (!empty($params['type'])) {
            $query->where('type', $params['type']);
        }

        // 名称搜索
        if (!empty($params['name'])) {
            $query->whereLike('name', '%' . $params['name'] . '%');
        }

        return $query->paginate([
            'list_rows' => $params['limit'] ?? 15,
            'page' => $params['page'] ?? 1
        ]);
    }

    // 获取文件夹树形结构
    public static function getFolderTree($userId, $parentId = 0)
    {
        $folders = self::where('create_by', $userId)
            ->where('type', self::TYPE_FOLDER)
            ->where('parent_id', $parentId)
            ->order('name', 'asc')
            ->select();

        $tree = [];
        foreach ($folders as $folder) {
            $node = [
                'id' => $folder['id'],
                'name' => $folder['name'],
                'children' => self::getFolderTree($userId, $folder['id'])
            ];
            $tree[] = $node;
        }

        return $tree;
    }

    // 创建文件夹
    public static function createFolder($data)
    {
        $data['type'] = self::TYPE_FOLDER;
        $data['size'] = 0;
        
        return self::create($data);
    }

    // 上传文件
    public static function uploadFile($data)
    {
        $data['type'] = self::TYPE_FILE;
        
        return self::create($data);
    }

    // 获取文件夹大小
    public function getFolderSize()
    {
        if ($this->type == self::TYPE_FILE) {
            return $this->size;
        }

        $size = 0;
        $children = $this->children;
        foreach ($children as $child) {
            $size += $child->getFolderSize();
        }

        return $size;
    }

    // 移动文件/文件夹
    public function moveTo($targetFolderId)
    {
        $this->parent_id = $targetFolderId;
        return $this->save();
    }

    // 复制文件/文件夹
    public function copyTo($targetFolderId, $userId)
    {
        $newItem = $this->replicate();
        $newItem->parent_id = $targetFolderId;
        $newItem->create_by = $userId;
        $newItem->save();

        if ($this->type == self::TYPE_FOLDER) {
            $children = $this->children;
            foreach ($children as $child) {
                $child->copyTo($newItem->id, $userId);
            }
        }

        return $newItem;
    }

    // 搜索文件
    public static function searchFiles($userId, $keyword)
    {
        return self::where('create_by', $userId)
            ->whereLike('name', '%' . $keyword . '%')
            ->order('type', 'asc')
            ->order('update_time', 'desc')
            ->select();
    }

    // 获取用户网盘使用情况
    public static function getUserDiskUsage($userId)
    {
        $total = self::where('create_by', $userId)
            ->where('type', self::TYPE_FILE)
            ->sum('size');

        return [
            'used' => $total,
            'total' => 1024 * 1024 * 1024, // 1GB
            'percentage' => round(($total / (1024 * 1024 * 1024)) * 100, 2)
        ];
    }

    // 文件类型搜索器
    public function searchTypeAttr($query, $value)
    {
        return $query->where('type', $value);
    }

    // 可见性搜索器
    public function searchVisibilityAttr($query, $value)
    {
        return $query->where('visibility', $value);
    }

    // 名称搜索器
    public function searchNameAttr($query, $value)
    {
        return $query->whereLike('name', '%' . $value . '%');
    }

    // 创建时间范围搜索器
    public function searchCreateTimeAttr($query, $value)
    {
        return $query->whereBetween('create_time', $value);
    }

    // 文件大小范围搜索器
    public function searchSizeAttr($query, $value)
    {
        return $query->whereBetween('size', $value);
    }

    // 获取文件完整路径
    public function getFullPath()
    {
        $path = $this->name;
        $parent = $this->parent;
        
        while ($parent) {
            $path = $parent->name . '/' . $path;
            $parent = $parent->parent;
        }

        return '/' . $path;
    }

    // 检查是否有权限访问
    public function canAccess($userId)
    {
        if ($this->visibility == self::VISIBILITY_PUBLIC) {
            return true;
        }

        if ($this->create_by == $userId) {
            return true;
        }

        // TODO: 检查共享权限
        return false;
    }

    // 获取文件下载链接
    public function getDownloadUrl()
    {
        if ($this->type != self::TYPE_FILE) {
            return '';
        }

        return '/api/disk/download/' . $this->id;
    }

    // 获取文件预览链接
    public function getPreviewUrl()
    {
        if ($this->type != self::TYPE_FILE) {
            return '';
        }

        $ext = strtolower(pathinfo($this->name, PATHINFO_EXTENSION));
        $supportPreview = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'txt', 'doc', 'docx', 'xls', 'xlsx'];

        if (in_array($ext, $supportPreview)) {
            return '/api/disk/preview/' . $this->id;
        }

        return '';
    }

    // 获取文件图标
    public function getIcon()
    {
        if ($this->type == self::TYPE_FOLDER) {
            return 'folder';
        }

        $ext = strtolower(pathinfo($this->name, PATHINFO_EXTENSION));
        $icons = [
            'pdf' => 'file-pdf',
            'doc' => 'file-word',
            'docx' => 'file-word',
            'xls' => 'file-excel',
            'xlsx' => 'file-excel',
            'ppt' => 'file-ppt',
            'pptx' => 'file-ppt',
            'jpg' => 'file-image',
            'jpeg' => 'file-image',
            'png' => 'file-image',
            'gif' => 'file-image',
            'zip' => 'file-zip',
            'rar' => 'file-zip',
            'txt' => 'file-text',
            'mp4' => 'file-video',
            'mp3' => 'file-audio',
        ];

        return $icons[$ext] ?? 'file-unknown';
    }

    // 批量删除文件/文件夹
    public static function batchDelete($ids, $userId)
    {
        return self::whereIn('id', $ids)
            ->where('create_by', $userId)
            ->useSoftDelete('delete_time', time())
            ->delete();
    }

    // 恢复删除的文件/文件夹
    public static function batchRestore($ids, $userId)
    {
        return self::onlyTrashed()
            ->whereIn('id', $ids)
            ->where('create_by', $userId)
            ->restore();
    }

    // 获取回收站文件
    public static function getRecycleBin($userId, $params = [])
    {
        return self::onlyTrashed()
            ->where('create_by', $userId)
            ->order('delete_time', 'desc')
            ->paginate([
                'list_rows' => $params['limit'] ?? 15,
                'page' => $params['page'] ?? 1
            ]);
    }
}